package com.xh.core.util;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.aspose.pdf.devices.JpegDevice;
import com.aspose.pdf.devices.Resolution;
import com.aspose.slides.Presentation;
import com.aspose.words.*;
import com.aspose.words.Shape;
import com.google.common.io.Files;
import com.mzlion.easyokhttp.HttpClient;
import com.xh.core.handler.WordReplaceWithDocEvaluator;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/11/8 14:44
 **/
@Data
public class OfficeUtils {

    private static final String QUESTION_COPYRIGHT_REGEXRULE = "声明：试题解析著作权属菁优网所有，未经书面同意，不得复制发布|日期：[\\S\\s]*；用户：[\\S\\s]*；邮箱：[\\S\\s]*；学号：[\\S\\s]*";
    private static final Pattern QUESTION_COPYRIGHT_PATTERN = Pattern.compile(QUESTION_COPYRIGHT_REGEXRULE);

    static {
        try {
            InputStream wordsLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.words.license.xml");// 凭证文件
            InputStream slidesLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.slides.license.xml");// 凭证文件
            InputStream cellsLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.cells.license.xml");// 凭证文件
            InputStream pdfsLicense = OfficeUtils.class.getClassLoader().getResourceAsStream("aspose.pdf.license.xml");// 凭证文件


            com.aspose.slides.License slidesLic = new com.aspose.slides.License();
            slidesLic.setLicense(slidesLicense);
            com.aspose.words.License wordsLic = new com.aspose.words.License();
            wordsLic.setLicense(wordsLicense);
            com.aspose.cells.License cellsLic = new com.aspose.cells.License();
            cellsLic.setLicense(cellsLicense);
            com.aspose.pdf.License pdfLic = new com.aspose.pdf.License();
            pdfLic.setLicense(pdfsLicense);

            //com.aspose.words.FontSettings.getDefaultInstance().setFontsFolder("/Users/david/Documents/Fonts", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * word转pdf
     *
     * @param inPath
     * @param outPath
     */
    public static boolean word2pdf(String inPath, String outPath, com.aspose.words.PdfSaveOptions options) {
        try {
            long old = System.currentTimeMillis();
            // 新建一个空白pdf文档
            File file = new File(outPath + ".tmp");
            FileOutputStream os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(inPath);
            if (options == null) {
                options = new com.aspose.words.PdfSaveOptions();
            }
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            doc.save(os, options);
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            // 转化用时
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * word转Png
     *
     * @param inPath
     * @param outPath
     */
    public static String word2png(String rootPath, String inPath, String outPath, com.aspose.words.ImageSaveOptions options) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            long old = System.currentTimeMillis();
            File fileDir = new File(rootPath + outPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            Document doc = new Document(rootPath + inPath); // Address是将要被转化的word文档
            if (options == null) {
                options = new com.aspose.words.ImageSaveOptions(SaveFormat.PNG);
                options.setResolution(128);
                options.setPrettyFormat(true);
                options.setUseAntiAliasing(true);
            }
            for (int i = 0; i < doc.getPageCount(); i++) {
                String pngPath = outPath + i + ".png";
                options.setPageIndex(i);
                doc.save(rootPath + pngPath, options);
                stringBuffer.append(pngPath).append(",");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            long now = System.currentTimeMillis();
            // 转化用时
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
            return stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * pdf转Png
     *
     * @param inPath
     * @param outPath
     */
    public static String pdf2jpg(String rootPath, String inPath, String outPath) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            long old = System.currentTimeMillis();
            File fileDir = new File(rootPath + outPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(rootPath + inPath);
            //图片宽度：800
            //图片高度：100
            // 分辨率 130
            //Quality [0-100] 最大100
            //例： new JpegDevice(800, 1000, resolution, 90);
            Resolution resolution = new Resolution(130);
            JpegDevice jpegDevice = new JpegDevice(resolution);
            for (int index = 1; index <= pdfDocument.getPages().size(); index++) {
                // 输出路径
                String imgPath = outPath + index + ".jpg";
                File file = new File(rootPath + imgPath);
                FileOutputStream fileOS = new FileOutputStream(file);
                jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOS);
                stringBuffer.append(imgPath).append(",");
                fileOS.close();
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
            return stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * html文件转word文件
     *
     * @param inPath
     * @param outPath
     * @param options
     * @return
     */
    public static boolean html2word(String inPath, String outPath, com.aspose.words.HtmlLoadOptions options) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            if (options == null) {
                options = new com.aspose.words.HtmlLoadOptions();
                options.setEncoding(Charset.forName("utf-8"));
                options.setLoadFormat(com.aspose.words.LoadFormat.HTML);

            }
            Document doc = new Document(inPath, options); // Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.DOC);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * html文本转换成word文档
     *
     * @param html
     * @param outPath
     * @return
     */
    public static boolean htmlText2Word(String html, String outPath, com.aspose.words.HtmlLoadOptions options) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            if (options == null) {
                options = new com.aspose.words.HtmlLoadOptions();
                options.setEncoding(Charset.forName("utf-8"));
                options.setLoadFormat(com.aspose.words.LoadFormat.HTML);

            }
            Document doc = new Document(file.getAbsolutePath(), options); // Address是将要被转化的word文档
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.insertHtml(html);
            doc.save(os, com.aspose.words.SaveFormat.DOC);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * word转html
     *
     * @param inPath
     * @param outPath
     */
    public static boolean word2html(String inPath, String outPath, com.aspose.words.HtmlSaveOptions options) {

        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            if (options == null) {
                options = new com.aspose.words.HtmlSaveOptions();
                //options.setResourceFolder("静态资源绝对路径");
                options.setOfficeMathOutputMode(HtmlOfficeMathOutputMode.IMAGE);
                options.setExportImagesAsBase64(true);
                options.setExportOriginalUrlForLinkedImages(false);
            }
            doc.save(os, options);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * ppt转pdf
     *
     * @param inPath
     * @param outPath
     */
    public static boolean ppt2pdf(String inPath, String outPath) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Presentation doc = new Presentation(inPath);// Address是将要被转化的word文档
            doc.save(os, com.aspose.slides.SaveFormat.Pdf);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

//    private static boolean ppt2png(){
//        FileInputStream is = null;
//        try {
//            is = new FileInputStream("slideshow.pptx");
//
//            SlideShow ppt = new SlideShow(is);
//            is.close();
//
//            double zoom = 2; // magnify it by 2
//            AffineTransform at = new AffineTransform();
//            at.setToScale(zoom, zoom);
//
//            Dimension pgsize = ppt.getPageSize();
//
//            Slide[] slide = ppt.getSlides();
//            for (int i = 0; i < slide.length; i++) {
//                BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
//                Graphics2D graphics = img.createGraphics();
//                graphics.setTransform(at);
//
//                graphics.setPaint(Color.white);
//                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
//                slide[i].draw(graphics);
//                FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
//                javax.imageio.ImageIO.write(img, "png", out);
//                out.close();
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        return  true;
//    }


    /**
     * ppt转html
     *
     * @param inPath
     * @param outPath
     * @return
     */
    public static boolean ppt2html(String inPath, String outPath) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Presentation doc = new Presentation(inPath); // Address是将要被转化的word文档
            doc.save(os, com.aspose.slides.SaveFormat.Html);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String ppt2png(String rootPath, String inPath, String outPath, String imgPath) {
        try {
            ppt2pdf(rootPath + inPath, rootPath + outPath);

//            return pdf2jpg(rootPath,outPath,imgPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * excel转pdf
     *
     * @param inPath
     * @param outPath
     */
    public static boolean excel2pdf(String inPath, String outPath, com.aspose.cells.PdfSaveOptions options) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            // load spreadsheet containing the chart
            com.aspose.cells.Workbook book = new com.aspose.cells.Workbook(inPath);

            if (options == null) {
                options = new com.aspose.cells.PdfSaveOptions();
                options.setOnePagePerSheet(true);
                options.setAllColumnsInOnePagePerSheet(true);
            }

            // get the chart present in first worksheet
            //com.aspose.cells.Chart chart = book.getWorksheets().get(0).getCharts().get(0);
            book.save(os, options);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * excel转html
     *
     * @param inPath
     * @param outPath
     */
    public static boolean excel2html(String inPath, String outPath, com.aspose.cells.HtmlSaveOptions options) {
        try {
            long old = System.currentTimeMillis();
            File file = new File(outPath + ".tmp"); // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            // load spreadsheet containing the chart
            com.aspose.cells.Workbook book = new com.aspose.cells.Workbook(inPath);

            if (options == null) {
                options = new com.aspose.cells.HtmlSaveOptions();
                options.setExportImagesAsBase64(true);
                options.setExportActiveWorksheetOnly(true);
            }

            // get the chart present in first worksheet
            //com.aspose.cells.Chart chart = book.getWorksheets().get(0).getCharts().get(0);
            book.save(os, options);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            os.close();
            // EPUB, XPS, SWF 相互转换
            Files.move(file, new File(outPath));
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 通用excel导入
     *
     * @param path
     * @return
     */
    public static List<Map<String, Object>> commonExcelImport(String path) {
        return commonExcelImport(path, null);
    }


    /**
     * 通用excel导入
     *
     * @param path
     * @return
     */
    public static List<Map<String, Object>> commonExcelImport(String path, ImportParams params) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (params == null) {
            params = new ImportParams();
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(new File(path));
            list = ExcelImportUtil.importExcel(is, Map.class, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return list;
    }


    /**
     * 通用导入，返回某实体对象列表
     * 对于有图片的列，图片左上角坐标需要位于所属单元格内
     *
     * @param path
     * @param params
     * @param clazz  自定义类，
     *               图片解析默认路径"/excel/upload/img"，程序需拥有读写权限
     *               普通类注解： @Excel(name = "a")
     *               图片字段注解： @Excel(name = "b", type = 2 ,imageType = 1)
     * @return
     */
    public static List commonExcelImport(String path, ImportParams params, Class clazz) {
        List list = new ArrayList<>();
        if (params == null) {
            params = new ImportParams();
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(new File(path));
            list = ExcelImportUtil.importExcel(is, clazz, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return list;
    }


    /**
     * 使用html的table生成excel表格
     * table的sheetName属性为sheet名称，必须指定
     *
     * @param html
     * @param outPath
     */
    public static boolean html2Excel(String html, String outPath) {
        try {
            Workbook workbook = ExcelXorHtmlUtil.htmlToExcel(html.toString(), ExcelType.XSSF);
            File savefile = new File(outPath + ".tmp");
            FileOutputStream fos = new FileOutputStream(savefile);
            workbook.write(fos);
            fos.close();
            Files.move(savefile, new File(outPath));
            return true;
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return false;
    }


    /**
     * 使用html的url的table生成excel表格
     * table的sheetName属性为sheet名称，必须指定
     *
     * @param url     url地址
     * @param charset 编码
     * @param outPath 输出文件
     */
    public static boolean htmlUrl2Excel(String url, String charset, String outPath) {
        try {
            String html = HttpClient
                    .textBody(url)
                    .charset(StringUtils.isEmpty(charset) ? "utf-8" : charset)
                    .text(null).execute().asString();

            Workbook workbook = ExcelXorHtmlUtil.htmlToExcel(html, ExcelType.XSSF);
            File savefile = new File(outPath + ".tmp");
            FileOutputStream fos = new FileOutputStream(savefile);
            workbook.write(fos);
            fos.close();
            Files.move(savefile, new File(outPath));
            return true;
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return false;
    }


    /**
     * latex转换成MathML
     *
     * @param content
     * @return
     */
    public static String convertLatex2MathML(String content) {
        long old = System.currentTimeMillis();
        String mathML = fmath.conversion.ConvertFromLatexToMathML.convertToMathML(content);
        mathML = mathML.replaceFirst("<math ", "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" ");
        long now = System.currentTimeMillis();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
        return mathML;
    }


    /**
     * latex转换成base64图片格式
     *
     * @param content
     * @return
     */
    public static String convertLatex2Base64Image(String content) {
        try {
            long old = System.currentTimeMillis();
            TeXFormula formula = new TeXFormula(content);
            // render the formla to an icon of the same size as the formula.
            TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
            // insert a border
            icon.setInsets(new Insets(5, 5, 5, 5));
            // now create an actual image of the rendered equation
            BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_BYTE_GRAY);
            Graphics2D g2 = image.createGraphics();
            g2.setColor(Color.white);
            g2.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
            JLabel jl = new JLabel();
            jl.setForeground(new Color(0, 0, 0));
            icon.paintIcon(jl, g2, 0, 0);
            // at this point the image is created, you could also save it with ImageIO
            // saveImage(image, "png", "F:\\b.png");
            // ImageIO.write(image, "png", new File("F:\\c.png"));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "png", outputStream);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            byte[] buffer = outputStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return ("data:image/png;base64," + encoder.encode(buffer));
        } catch (Exception e) {
            // e.printStackTrace();
            // ExceptionUtil.log(log, e);
            System.err.println("公式解析有误：\n" + content);
            // e.printStackTrace();
            return null;
        }
    }

    /**
     * word文档合并，保持页码连续
     *
     * @param oriFiles
     * @param output
     * @return
     */
    public static String wordsMerge(List<String> oriFiles, String output) {
        try {
            Document docOutput = new Document();
            docOutput.removeAllChildren();
            for (String oriFilePath : oriFiles) {
                FileInputStream fs1 = new FileInputStream(new File(oriFilePath));
                Document doc1 = new Document(fs1);
                docOutput.appendDocument(doc1, ImportFormatMode.KEEP_DIFFERENT_STYLES);
                fs1.close();
            }
            docOutput.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS);
            docOutput.getFirstSection().getPageSetup().setPageStartingNumber(1);
            docOutput.save(output, SaveFormat.DOCX);
            return output;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * word文档插入合并
     *
     * @param template
     * @param output
     * @param mergedFiles
     * @return
     */
    public static String wordsInsert(String template, String output, Map<String, String> mergedFiles) {
        try {
            Document doc = new Document(template);
            FindReplaceOptions options = new FindReplaceOptions();
            for (String key : mergedFiles.keySet()) {
                Document docSub = new Document(mergedFiles.get(key));
                ParagraphCollection paragraphs = docSub.getFirstSection().getBody().getParagraphs();
                for (Paragraph paragraph : paragraphs) {
                    String text = paragraph.getText();
                    if (QUESTION_COPYRIGHT_PATTERN.matcher(text).find()) {
                        paragraph.remove();
                    }
                }
                options.setReplacingCallback(new WordReplaceWithDocEvaluator(options, docSub));
                doc.getRange().replace("<" + key + ">", "", options);
            }

            //统一字体字号
           /* NodeCollection shapes = doc.getChildNodes(NodeType.PARAGRAPH,true);
            for(int i=0;i<shapes.getCount();i++) {
                Paragraph tocItem=(Paragraph)shapes.get(i);
                if (tocItem != null) {
                    //设置每行目录样式
                    for (Run run : tocItem.getRuns()) {
                        run.getFont().setName("新宋体");
                        run.getFont().setSize(10.5);
                    }
                }
            }*/
            doc.save(output, SaveFormat.DOCX);
        } catch (Exception ex) {

        }
        return output;
    }

    public static void getMathTypeCode() {
        //OLE对象测试
        try {
            long old = System.currentTimeMillis();
//            Document doc = new Document("/Users/david/Documents/依米书院上半年教师专业能力测试—高中数学（含答案）(1).docx"); // Address是将要被转化的word文档
            Document doc = new Document("/Users/david/Documents/Doc4.docx"); // Address是将要被转化的word文档
            NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
            System.out.println(shapes.getCount());
            for (int i = shapes.getCount() - 1; i >= 0; i--) {
                Shape shape = (Shape) shapes.get(i);
                System.out.println(i + "=" + shape.getNodeType());
                if (shape.getOleFormat() != null) {
                    OleFormat oleFormat = shape.getOleFormat();

                    System.out.println(oleFormat.getProgId());

                    byte[] oleBytes = oleFormat.getOleEntry("\u0001Ole");
                    byte[] compObjBytes = oleFormat.getOleEntry("\u0001CompObj");
                    byte[] objInfoBytes = oleFormat.getOleEntry("\u0003ObjInfo");
                    byte[] olePresBytes = oleFormat.getOleEntry("\u0002OlePres000");
                    byte[] EquationNativeBytes = oleFormat.getOleEntry("Equation Native");
                    //"\u0001CompObj","\u0003ObjInfo","\u0002OlePres000","Equation Native";
//                    System.out.println("Ole："+new String(oleBytes,"utf-8"));
//                    System.out.println("CompObj："+new String(compObjBytes,"utf-8"));
//                    System.out.println("ObjInfo："+new String(objInfoBytes,"utf-8"));
//                    System.out.println("OlePres000："+new String(olePresBytes,"utf-8"));
                    String equationNative = new String(EquationNativeBytes, "utf-8");
//                    System.out.println("Equation Native："+equationNative);

                    String startStr = "Input Language";
                    int startIndex = equationNative.indexOf(startStr) + startStr.length() + 1;
                    String formula = "$" + equationNative.substring(startIndex, equationNative.indexOf("\u0000", startIndex)) + "$";
                    System.out.println(formula);
                    Run text = new Run(doc, formula);
                    //shape.insertAfter(text,null);
                    DocumentBuilder db = new DocumentBuilder(doc);
                    db.moveTo(shape);
                    db.insertNode(text);
                    shape.remove();
//                    FileUtils.saveFile(oleBytes,"/Users/david/Documents/Doc4_ole.bin");
//                    FileUtils.saveFile(compObjBytes,"/Users/david/Documents/Doc4_CompObj.bin");
//                    FileUtils.saveFile(objInfoBytes,"/Users/david/Documents/Doc4_ObjInfo.bin");
//                    FileUtils.saveFile(olePresBytes,"/Users/david/Documents/Doc4_OlePres000.bin");
                    FileUtils.saveFile(EquationNativeBytes, "/Users/david/Documents/Doc4_EquationNativeBytes_" + i + ".bin");
                    oleFormat.save("/Users/david/Documents/Doc4_" + i + "." + oleFormat.getSuggestedExtension());
                    //System.out.println(oleFormat.getOleEntry("Equation.DSMT4"));
                }
            }
            doc.save("/Users/david/Documents/依米书院111111.docx", com.aspose.words.SaveFormat.DOCX);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createTable(DocumentBuilder builder) {
        try {
            builder.startTable();
            builder.getFont().setSize(10.5);
            builder.getFont().setName("宋体");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createCellWriteContent(DocumentBuilder builder, double cellWidth, String content, boolean endRow) throws Exception {

        builder.insertCell();
        builder.getFont().setSize(11);
        builder.getFont().setBold(false);
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setLeftPadding(0);
        builder.getCellFormat().setRightPadding(0);
        builder.getCellFormat().setWidth(cellWidth);
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
        builder.write(content);
        if (endRow) {
            builder.endRow();
        }
    }

    public static void createCellWriteContent(DocumentBuilder builder, double cellWidth, Integer Alignment, String content, boolean endRow) throws Exception {

        builder.insertCell();
        builder.getFont().setSize(11);
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setLeftPadding(0);
        builder.getCellFormat().setRightPadding(0);
        builder.getCellFormat().setWidth(cellWidth);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.getParagraphFormat().setAlignment(Alignment);
        builder.write(content);
        if (endRow) {
            builder.endRow();
        }
    }

    public static void createCellInsertHtml(DocumentBuilder builder, double cellWidth, double leftPadding, String content, boolean endRow) throws Exception {

        builder.insertCell();
        builder.getFont().setSize(10.5);
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setLeftPadding(leftPadding);
        builder.getCellFormat().setRightPadding(0);
        builder.getCellFormat().setWidth(cellWidth);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
        builder.insertHtml(content);
        if (endRow) {
            builder.endRow();
        }
    }


    public static void createBlankRow(DocumentBuilder builder, double cellWidth, double height, boolean endRow) throws Exception {

        builder.insertCell();
        builder.getFont().setSize(10.5);
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setLeftPadding(0);
        builder.getCellFormat().setRightPadding(0);
        builder.getCellFormat().setWidth(cellWidth);
//        builder.getRowFormat().setHeight(height);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
        builder.write("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        if (endRow) {
            builder.endRow();
        }
    }

    public static void createTab(DocumentBuilder builder, int tabNum) {
        TabStopCollection tabStops = builder.getParagraphFormat().getTabStops();
        tabStops.clear();
        if (tabNum == 1) {
            tabStops.add(245, 0, 0);
        } else if (tabNum == 3) {
            tabStops.add(127.5, 0, 0);
            tabStops.add(245, 0, 0);
            tabStops.add(362.5, 0, 0);
        }
    }

    public static void createCloneTab(DocumentBuilder builder, int tabNum) {
        TabStopCollection tabStops = builder.getParagraphFormat().getTabStops();
        tabStops.clear();
        if (tabNum == 1) {
            tabStops.add(19, 0, 0);
            tabStops.add(245, 0, 0);
        } else if (tabNum == 3) {
            tabStops.add(19, 0, 0);
            tabStops.add(127.5, 0, 0);
            tabStops.add(245, 0, 0);
            tabStops.add(362.5, 0, 0);
        }
    }

    public static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
        // Create a watermark shape. This will be a WordArt shape.
        // You are free to try other shape types as watermarks.
        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);

        // Set up the text of the watermark.
        watermark.getTextPath().setText(watermarkText);
        watermark.getTextPath().setFontFamily("宋体");
        watermark.setWidth(200);
        watermark.setHeight(50);
        // Text will be directed from the bottom-left to the top-right corner.
        watermark.setRotation(-40);
        // Remove the following two lines if you need a solid black text.
        watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more Word-style watermark
        watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more Word-style watermark

        // Place the watermark in the page center.
        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
        watermark.setWrapType(WrapType.NONE);
        watermark.setVerticalAlignment(VerticalAlignment.CENTER);
        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // Create a new paragraph and append the watermark to this paragraph.
        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.appendChild(watermark);

        // Insert the watermark into all headers of each document section.
        for (Section sect : doc.getSections()) {
            // There could be up to three different headers in each section, since we want
            // the watermark to appear on all pages, insert into all headers.
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
        }
    }

    private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {
        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);

        if (header == null) {
            // There is no header of the specified type in the current section, create it.
            header = new HeaderFooter(sect.getDocument(), headerType);
            sect.getHeadersFooters().add(header);
        }

        // Insert a clone of the watermark into the header.
        header.appendChild(watermarkPara.deepClone(true));
    }

    public static void createTable(String path) throws Exception {
        Document doc = new Document(path);

        doc.setNodeChangingCallback(new HandleNodeChangingFontChanger(10.5));
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.getPageSetup().setLeftMargin(60);
        builder.getPageSetup().setRightMargin(60);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.moveToDocumentEnd();
//        // 设置页眉页脚
//        builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
//        builder.insertImage("C:\\Users\\Administrator\\Desktop\\logo.png", 261, 30);
        builder.moveToDocumentEnd();
        Table table = builder.startTable();
        builder.getFont().setSize(10);
        builder.getFont().setName("Calibri");
        builder.insertCell();
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setLeftPadding(0);
        builder.getCellFormat().setWidth(480);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.write("\n\n\n\n\n\n\n\n\n\n\n\n\n");
        builder.endRow();


        builder.insertCell();
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.white);
        builder.getCellFormat().setWidth(480);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.insertHtml("<p><p><p><p><p><p><p><p>");
        builder.endRow();

        builder.insertCell();
        builder.getCellFormat().getBorders().setLineStyle(LineStyle.SINGLE);
        builder.getCellFormat().getBorders().setColor(Color.black);
        builder.getCellFormat().setWidth(480);
        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
        builder.getParagraphFormat().setLineSpacing(18);
        builder.insertHtml("D.第aasdasdfasf四四四");
        builder.endRow();
//        doc.getRange().replace("\t", "",new FindReplaceOptions());
//        这里就是根据设置的宽度固定表格单元格的宽度的核心代码
        builder.endTable();
        table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
        doc.save(path, com.aspose.words.SaveFormat.DOCX);

    }

    /**
     * 合并两个doc文件
     *
     * @param srcPath
     * @param dstPath
     * @throws Exception
     */
    public static void mergeDoc(String srcPath, String dstPath) throws Exception {
        Document srcDoc = new Document(srcPath);
        Document dstDoc = new Document(dstPath);
        // 清空第一行
        dstDoc.getFirstSection().getBody().getFirstParagraph().remove();
        for (Section section : srcDoc.getSections()) {
            dstDoc.getFirstSection().appendContent(section);
        }
        dstDoc.save(dstPath, com.aspose.words.SaveFormat.DOCX);
    }

    public static int base64ToImg(String data) throws IOException {
        byte[] strBase64 = new BASE64Decoder().decodeBuffer(data);
        try {
            InputStream is = new ByteArrayInputStream(strBase64);
            BufferedImage image = ImageIO.read(is);
            return image.getWidth();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    public static void imgCenter() throws Exception {
        Document doc = new Document("D:\\七年级期中测试考试卷.doc");
        int lineHeight = -2;
        NodeCollection childNodes = doc.getChildNodes(NodeType.TABLE, true);
        for (int i = 0; i < childNodes.getCount(); i++) {
            //删除空行
            Table paragraph = (Table) childNodes.get(i);
            if (!paragraph.hasChildNodes()) {
                paragraph.remove();
            }
            NodeCollection collection = paragraph.getChildNodes(NodeType.SHAPE, true);
            for (int j = 0; j < collection.getCount(); j++) {
                Shape shape = (Shape) collection.get(j);
                shape.getFont().setPosition(-shape.getHeight() / 2 - lineHeight);
            }
        }
        doc.save("D:\\b.doc", com.aspose.words.SaveFormat.DOCX);
    }

    public static void setPageMargin() throws Exception {
        String path = "D:\\PaperTemplate.doc";
        Document doc = new Document(path);
        for (Section section : doc.getSections()) {
            section.getPageSetup().setLeftMargin(57);
            section.getPageSetup().setRightMargin(57);
        }
        doc.save(path, com.aspose.words.SaveFormat.DOCX);
    }

    public static void setFontBackGroup() throws Exception {
        String path = "D:\\b.doc";
        String imgPath = "D:\\back.png";
        Document doc = new Document(path);
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.moveToDocumentEnd();
//        Shape shape = builder.insertImage(imgPath,25,25.0,15,20,100,30,WrapType.INLINE);
        Shape shape = new Shape(doc, ShapeType.IMAGE);
        shape.getImageData().setImage(imgPath);
        // 图片沉在文字下方
        shape.setBehindText(true);
        shape.setTop(4);
        shape.setWidth(200);
        shape.setHeight(30);
        shape.setTitle("dsafdasd");
        shape.getTextBox();
        builder.insertNode(shape);
        builder.getFont().setSize(18);
        builder.getFont().setBold(true);
//        builder.getFont().setColor(Color.white);
        builder.getCurrentParagraph().getParagraphFormat().setLeftIndent(30);
        builder.write("知识点");
        doc.save(path, com.aspose.words.SaveFormat.DOCX);
    }

    public static void setPageSize() throws Exception {
        String path = "";
        Document doc = new Document(path);
        for (Section section : doc.getSections()) {
            PageSetup pageSetup = section.getPageSetup();
            pageSetup.setPageWidth(36.4);
            pageSetup.setPageHeight(25.7);
            pageSetup.setOrientation(Orientation.LANDSCAPE);
            pageSetup.getTextColumns().setCount(2);
            pageSetup.getTextColumns().setEvenlySpaced(true);
            pageSetup.getTextColumns().setLineBetween(true);
        }
    }

    public static void main(String[] args) throws Exception {
        String path = "D:\\英语导出测试 (5).doc";
        System.out.println(!RegexUtils.Match("english3","english|yingyu"));
//        Document doc = new Document(path);
//        DocumentBuilder builder = new DocumentBuilder(doc);
//        builder.moveToDocumentEnd();
//        builder.getPageSetup().setLeftMargin(65);
//        builder.getPageSetup().setRightMargin(65);
//        builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.MULTIPLE);
//        builder.getParagraphFormat().setLineSpacing(18);
//        int lineHeight = -4;
//        NodeCollection childNodes = doc.getChildNodes(NodeType.PARAGRAPH, true);
//        for (int i = 0; i < childNodes.getCount(); i++) {
//            //删除空行
//            Paragraph paragraph = (Paragraph) childNodes.get(i);
////            if (!paragraph.hasChildNodes()) {
////                paragraph.remove();
////            }
//            NodeCollection collection = paragraph.getChildNodes(NodeType.SHAPE, true);
//            for (int j = 0; j < collection.getCount(); j++) {
//                Shape shape = (Shape) collection.get(j);
//                System.out.println(shape.getFont().getPosition() + "   " + (-shape.getHeight() / 2 - lineHeight));
//                shape.getFont().setPosition(-shape.getHeight() / 2 - lineHeight);
////                shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.COLUMN);
////                shape.setHorizontalAlignment(HorizontalAlignment.CENTER);
////                shape.setVerticalAlignment(VerticalAlignment.CENTER);
//            }
//        }
//        doc.save("D:\\PaperTemplate.doc", SaveFormat.DOCX);
    }
}
